package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.dto.HandleAlertDataDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-28
 */
@Slf4j
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 分页查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        return alertDataMapper.selectAlertDataList(alertData);
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 查询报警数据
     */
    @Override
    public List<AlertData> getByDeviceAndTime(String deviceName, String startTime, String endTime) {
        try {
            log.info("报警数据查询: deviceName={}, startTime={}, endTime={}", deviceName, startTime, endTime);

            List<AlertData> result = alertDataMapper.selectByDeviceAndTime(deviceName, startTime, endTime);
            log.info("查询到 {} 条报警数据", result.size());
            return result;

        } catch (Exception e) {
            log.error("通过设备名称和报警时间查询失败", e);
            throw new RuntimeException("查询报警数据失败", e);
        }
    }

    /**
     * 处理报警数据
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleAlertData(HandleAlertDataDTO dto) {
        // 验证报警数据是否存在
        AlertData alertData = this.getById(dto.getId());
        if (alertData == null) {
            throw new RuntimeException("报警数据不存在");
        }

        if (alertData.getStatus() == 1) {
            throw new RuntimeException("该报警已处理，无法重复处理");
        }

        // 更新处理信息
        AlertData updateData = new AlertData();
        updateData.setId(dto.getId());
        updateData.setProcessingResult(dto.getProcessingResult());

        // 处理时间：优先使用传入的时间，如果没有则使用当前时间
        if (dto.getProcessingTime() != null) {
            updateData.setProcessingTime(dto.getProcessingTime());
        } else {
            updateData.setProcessingTime(LocalDateTime.now());
        }
        updateData.setStatus(1); // 设置为已处理状态
        updateData.setUpdateTime(new Date());
        updateData.setProcessorId(getCurrentUserId());
        updateData.setProcessorName(getCurrentUserName());

        boolean success = this.updateById(updateData);
        if (!success) {
            throw new RuntimeException("处理报警数据失败");
        }
        log.info("报警数据处理成功，ID: {}", dto.getId());
    }
    /**
     * 获取当前用户ID
     * @return
     */
    private Long getCurrentUserId() {
        return SecurityUtils.getUserId();
    }
    /**
     * 获取当前用户名
     */
    private String getCurrentUserName() {
        return SecurityUtils.getUsername();
    }

}
